import { Button, Radio, Alert } from 'antd'
import { colors } from '@/desktop/styles'
import { Target } from '../logics'
import { ChooseTargetByTag } from './choose-target-by-tag'
import { ChooseTargetGroups } from './choose-target-groups'
import { commonS } from './style'
import { type Editing } from './index'

export function ChooseTarget({
  editing,
  goPrev: rawGoPrev,
  goNext: rawGoNext,
}: {
  editing: Editing
  goPrev: (updates: Partial<Pick<Editing, 'targetType' | 'tagIds' | 'contacts'>>) => void
  goNext: (updates: Pick<Editing, 'targetType' | 'tagIds' | 'contacts'>) => void
}) {
  const [targetType, setTargetType] = useState(editing.targetType)
  const [tagIds, setTagIds] = useState(editing.tagIds)
  const [contacts, setContacts] = useState(editing.contacts)
  function goPrev() {
    rawGoPrev({ targetType, tagIds, contacts })
  }
  function goNext() {
    rawGoNext({ targetType, tagIds, contacts })
  }
  const canGoNext =
    targetType === Target.全部客户 ||
    (targetType === Target.标签客户 ? tagIds.length > 0 : contacts.length > 0)

  return <div css={commonS.wrap}>
    <div css={s.type}>
      <Radio.Group
        optionType="button"
        options={[
          // 注：暂不支持“手动选择客户”进行发送
          { label: '标签客户', value: Target.标签客户 },
          { label: '全部客户', value: Target.全部客户 },
          { label: '群聊', value: Target.群 },
        ]}
        value={targetType}
        onChange={e => setTargetType(e.target.value as Target)}
      />
    </div>

    <div css={[commonS.tips, s.tips]}>
      {targetType === Target.标签客户 ? '群发给打了指定标签的客户' : null}
      {targetType === Target.群 ? '群发到选中的群聊' : null}
    </div>

    {targetType === Target.全部客户 ? (
      <Alert
        css={s.allExternalTips}
        message="此选项会把消息发给所有客户"
        description="建议优先选择『打标签的客户』"
        type="info"
        showIcon
      />
    ) : null}

    {targetType === Target.标签客户 ? (
      <ChooseTargetByTag editing={editing} tagIds={tagIds} setTagIds={setTagIds} />
    ) : null}

    {targetType === Target.群 ? (
      <ChooseTargetGroups qywxs={editing.qywxs} contacts={contacts} setContacts={setContacts} />
    ) : null}

    <footer css={commonS.footer}>
      <Button size="large" onClick={goPrev}>
        上一步
      </Button>
      <Button type="primary" size="large" disabled={!canGoNext} onClick={goNext}>
        下一步
      </Button>
    </footer>
  </div>
}

const s = {
  type: css`
    text-align: center;
    padding: 20px 0 12px;
  `,
  tips: css`
    text-align: center;
  `,
  allExternalTips: css`
    width: 320px;
    margin: 20px auto 0;
    .second {
      color: ${colors.gray};
      font-size: 16px;
      margin-top: 6px;
    }
  `,
}
